<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>游戏大厅</title>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <!-- style CSS -->
    <link rel="stylesheet" href="css/index.css" type="text/css" media="all">
    <!-- google fonts -->
    <link href="//fonts.googleapis.com/css?family=Mukta:300,400,500" rel="stylesheet">

</head>
<body>
    <div class="main">
        <div class="container">
            <div class="message">
                <img src="images/bg.jpg">
                <div class="msg">
                    <p class="left">玩家昵称: &nbsp;&nbsp; </p>
                    <p class="right" id="player"></p>
                </div>
                <div class="msg">
                    <p class="left">玩家分数: &nbsp;&nbsp; </p>
                    <p class="right" id="score"></p>
                </div>
                <div class="msg">
                    <p class="left">比赛场次: &nbsp;&nbsp; </p>
                    <p class="right" id="counts"></p>
                </div>
                <div class="msg">
                    <p class="left">获胜场次: &nbsp;&nbsp; </p>
                    <p class="right" id="wincounts"></p>
                </div>

            </div>
            <div class="button">
                <button id="startMatch">开始匹配</button>
                <button id="stopMatch">停止匹配</button>
            </div>
        </div>
        <div class="playerList">
            <p>当前在线用户</p>
            <div class="players"></div>
        </div>
    </div>

    <script src="js/jquery.min.js"></script>
    <script>
        // 获取当前用户的信息
        $.ajax({
            url: 'user/getuserinfo',
            type: 'get',
            success: function (result) {
                let player = document.querySelector("#player");
                let score = document.querySelector("#score");
                let counts = document.querySelector("#counts");
                let wincounts = document.querySelector("#wincounts");
                if (result.state == 'SUCCESS'){
                    let user = result.data;
                    player.innerHTML = user.nickname;
                    score.innerHTML = user.score;
                    counts.innerHTML = user.totalCount;
                    wincounts.innerHTML = user.winCount;
                }
            },
            error: function () {
                alert("获取用户信息失败")
            }
        })

        // 拉取在线用户信息
        $.ajax({
            url: 'user/getonlineUsers',
            type: 'get',
            success: function (result) {
                if (result.state == 'SUCCESS'){
                    let users = result.data;
                    let players = document.querySelector(".players");
                    for(var user of users){
                        // 遍历将 user对象挂载到页面上
                        let player = document.createElement("div");
                        player.className = 'player';

                        let photo = document.createElement('img');
                        photo.src = user.photo;
                        let name = document.createElement('span');
                        name.innerHTML = user.nickname;
                        let state = document.createElement('span');
                        let button = document.createElement('button')
                        if(user.state == 'online'){
                            state.innerHTML = '在线'
                            state.className = 'online'
                            button.innerHTML = '挑战他'
                            button.className = 'challenge'
                            button.setAttribute("userid", user.userId);// 设置属性值
                            button.setAttribute("onclick", "chanllenge(this)");// 设置属性值
                        }else if (user.state == 'game'){
                            state.innerHTML = '游戏中...'
                            state.className = 'game'
                            button.innerHTML = '观战'
                            button.className = 'watch'
                            button.setAttribute("roomid", user.roomId);// 设置房间号的属性值
                            button.setAttribute("onclick", "watchgame(this)");// 设置点击属性值
                        }
                        player.appendChild(photo);
                        player.appendChild(name);
                        player.appendChild(state);
                        player.appendChild(button);
                        players.appendChild(player)
                    }
                }
            }
        })

        let startMatch = document.querySelector("#startMatch");
        let stopMatch = document.querySelector("#stopMatch");

        // 初始化 webSocket, 实现匹配机制
        let url = 'ws://'+ location.host +'/match';
        let websocket = new WebSocket(url);
        websocket.onopen = function () {
            console.log("match onopen");
        }
        websocket.onclose = function () {
            console.log("match onclose");
        }
        websocket.onerror = function () {
            console.log("match onerror");
        }
        websocket.onmessage = function (response) {
            // 收到消息
            let data = JSON.parse(response.data);// 得到数据载荷
            if (data.state == 'FAIL'){
                if (data.reason == 'outline'){
                    alert("对方离线, 无法邀请对方")
                    window.location.href = 'index.html'
                }else if (data.reason == 'game'){
                    alert("对方已在游戏中")
                    window.location.href = 'index.html'
                }else if(data.reason == 'notExit'){
                    alert("该游戏房间不存在")
                    window.location.href = 'index.html'
                }else {
                    console.log("游戏大厅中接收到了失败的响应")
                    return;
                }
            }else if(data.state == 'EXIST'){
                alert('该账号已在别地登录! 如非本人操作, 请及时检查帐号邮箱绑定并修改密码')
                window.location.href = 'login.html'
            }
            if (data.message == 'startMatch'){
                console.log('进入匹配队列')
                startMatch.innerHTML = '匹配中...'
            }else if (data.message == 'stopMatch'){
                console.log('从匹配队列中移除')
                startMatch.innerHTML = '开始匹配'
            }else if (data.message == 'matchSuccess'){
                console.log('匹配到对手')
                window.location.href = 'gameRoom.html'
            }else if(data.message == 'challenge'){
                // 将文字内容改为  等待对方接受邀请
                let chanBtn = $("button[userid=" + data.userId +"]")
                chanBtn.html('等待对方接受邀请...')
            }else if(data.message == 'waitAccept'){
                // 有人等待你接受邀请
                var msg = data.reason + "邀请您PK";
                if (confirm(msg) == true){
                    // 接受邀请   --    发送请求匹配两人进入房间
                    websocket.send(JSON.stringify({
                        message: 'acceptChallenge',
                        userId: data.userId
                    }))
                }else{
                    // 拒绝请求 --  发送请求拒绝
                    websocket.send(JSON.stringify({
                        message: 'refuseChallenge',
                        userId: data.userId
                    }))
                }
            }else if(data.message == 'refuseChallenge'){
                alert('对方拒绝了您的邀请')
                $("button[userid=" + data.userId + "]").html('挑战他')
            }else if(data.message == 'watch'){
                // 进入观战页面
                window.location.href = 'gameRoom.html?roomId=' + data.reason
            }else {
                console.log('收到了非法的响应, message' + data.message);
            }
        }
        // 监听页面关闭事件
        window.onbeforeunload = function () {
            websocket.close()
        }

        // 点击匹配, 发送请求
        $("#startMatch").click(function () {
            // 确认连接是否正常
            if (websocket.readyState == websocket.OPEN){
                console.log("开始匹配");
                websocket.send(JSON.stringify({
                    message: 'startMatch'
                }))
            } else {
                // 连接异常
                alert("当前连接已经断开, 请重新登录");
                window.location.href = 'login.html';
            }
        })
        // 取消匹配
        $("#stopMatch").click(function () {
            // 确认连接是否正常
            if (websocket.readyState == websocket.OPEN){
                console.log("停止匹配");
                websocket.send(JSON.stringify({
                    message: 'stopMatch'
                }))
            } else {
                // 连接异常
                alert("当前连接已经断开, 请重新登录");
                window.location.href = 'login.html';
            }
        })

        // 发起挑战
        function chanllenge(btn) {
            if (websocket.readyState == websocket.OPEN) {
                console.log("向" + $(btn).attr("userid") + "发起挑战");
                websocket.send(JSON.stringify({
                    message: 'challenge',
                    userId: $(btn).attr("userid")
                }))
            }
        }
        // 观战
        function watchgame(btn) {
            if (websocket.readyState == websocket.OPEN) {
                console.log("观战的房间号为: " + $(btn).attr("roomid"));
                websocket.send(JSON.stringify({
                    message: 'watch',
                    roomId: $(btn).attr("roomid")
                }))
            }
        }
    </script>
</body>
</html>